package com.zll.dms.service.impl;

import com.zll.dms.constants.Constants;
import com.zll.dms.exception.MyBaseException;
import com.zll.dms.mapper.UserMapper;
import com.zll.dms.model.User;
import com.zll.dms.pojo.param.RegisterParam;
import com.zll.dms.service.AuthService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Map;

@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private UserMapper userMapper;


    @Override
    public void checkCode(String email, String inputCode) {
        boolean checkPass = false;
        Session session = SecurityUtils.getSubject().getSession();
        Map<String, Object> codeMap = (Map<String, Object>) session.getAttribute(email);
        if (codeMap == null) {
            throw new MyBaseException("请先获取验证码");
        }
        String code = (String) codeMap.get("code");
        if (!StringUtils.equals(inputCode, code)) {
            throw new MyBaseException("验证码不正确");
        }
        Long createTime = (Long) codeMap.get("createTime");
        long now = Calendar.getInstance().getTimeInMillis();
        //当前时间超过预定过期时间=过期
        if (now > createTime + Constants.MAIL_CONTENT_CODE_EFFECTIVE) {
            throw new MyBaseException("验证码失效，请重新获取");
        }
    }

    @Override
    public void registerUser(RegisterParam registerParam) {
        //转化成user对象
        User user = new User();
        BeanUtils.copyProperties(registerParam, user);
        //持久化进数据库
        int insert = userMapper.addUser(user);
        //判断是否成功
        if (insert <= 0) {
            throw new MyBaseException("注册用户-持久化失败");
        }
    }

}
